import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zyf
 * @Date: 2024/04/25/15:47
 * @Description:
 */
public class ToStringUtil {

    public static String object2string(int level, Object object) {
        StringBuilder builder = new StringBuilder();
        if (object instanceof List) {
            level++;
            builder.append("[").append("\n");
            for (Object o : ((List<?>) object)) {
                tab(level, builder);
                builder.append(object2string(level, o));
            }
            tab(level, builder);
            builder.append("]");
        } else if (object instanceof Map) {
            level++;
            builder.append("{").append("\n");
            for (Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
                tab(level, builder);
                builder.append(entry.getKey()).append("=").append(object2string(level, entry.getValue()));
            }
            tab(level, builder);
            builder.append("}");
        } else if (object instanceof String) {
            List<String> strings = Arrays.stream(((String) object).split("\n")).filter(s -> !s.isEmpty()).collect(Collectors.toList());
            int n = strings.size();
            if (n > 1) {
                builder.append("\n");
                for (int i = 0; i < n - 1; i++) {
                    tab(level + 1, builder);
                    builder.append(strings.get(i)).append("\n");
                }
                builder.append(strings.get(n - 1));
            } else {
                builder.append(object);
            }
        } else {
            tab(level, builder);
            builder.append(object);
        }
        builder.append("\n");
        return builder.toString();
    }

    private static void tab(int level, StringBuilder builder) {
        for (int i = 0; i < level; i++) builder.append(" ");
    }
}
